<template>
  <div class="articleManager">
    <div class="operate">
      <div class="left">
        <span class="name">标题</span>
        <el-input
          v-model="searchParams.title"
          placeholder="请输入标题"
          clearable>
        </el-input>
        <span class="name">栏目</span>
        <el-select v-model="searchParams.type" clearable placeholder="请选择">
          <el-option
            v-for="item in columnList"
            :key="item.value"
            :label="item.name"
            :value="item.value">
          </el-option>
        </el-select>
        <el-button style="margin-left: 14px;" type="primary" @click="handleSearch">查询</el-button>
      </div>
      <div class="right">
        <el-button type="primary" @click="newItem">创建文章</el-button>
<!--        <el-button type="primary" @click="handleDeleteItem">批量删除</el-button>-->
      </div>
    </div>
    <el-table
      height="100"
      :data="tableData"
      stripe
      style="width: 100%">
      <el-table-column type="index" label="序号" width="50"></el-table-column>
      <el-table-column prop="title" label="文章标题" :show-overflow-tooltip="true"></el-table-column>
      <el-table-column label="文章栏目" width="80">
        <template slot-scope="scope">
          <span>{{findColumnName(scope.row.type)}}</span>
        </template>
      </el-table-column>
      <el-table-column label="置顶" width="60">
        <template slot-scope="scope">
          <span>{{scope.row.topping == '1' ? '是' : '否'}}</span>
        </template>
      </el-table-column>
      <el-table-column label="封面图" width="120">
        <template slot-scope="scope">
          <div style="display: flex; align-items: center;">
            <el-image
              v-if="scope.row.pic"
              :src="scope.row.pic"
              :preview-src-list="[scope.row.pic]"
              style="width: 95px; height: 46px">
            </el-image>
            <span v-else>-</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="releaseTime" label="发布时间" width="90"></el-table-column>
      <el-table-column prop="createTime" label="创建时间" width="140"></el-table-column>
      <el-table-column prop="createBy" label="素材来源" width="140"></el-table-column>
      <el-table-column fixed="right" label="操作" width="120">
        <template slot-scope="scope">
          <el-button type="text" size="small" @click="handleCheckItem(scope.row)">查看</el-button>
          <el-button type="text" size="small" @click="handleEditItem(scope.row)">编辑</el-button>
          <el-button type="text" size="small" @click="handleDeleteItem(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div class="pageContain">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="searchParams.pageNum"
        :page-size="searchParams.pageSize"
        :page-sizes="[100, 200, 300, 400]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total">
      </el-pagination>
    </div>
    <el-dialog
      :title="dialogTitle"
      :visible.sync="dialogVisible"
      :fullscreen="true"
      :before-close="handleCancel">
      <el-form
        ref="article"
        label-position="top"
        :model="articleFrom"
        :rules="articleRules"
        label-width="80px">
        <el-form-item label="文章标题" prop="title">
          <el-input v-model="articleFrom.title"></el-input>
        </el-form-item>

        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="文章栏目" prop="type">
              <el-select style="width: 160px;" v-model="articleFrom.type">
                <el-option
                  v-for="item in columnList"
                  :key="item.value"
                  :label="item.name"
                  :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="素材来源" prop="createBy">
              <el-input
                style="width: 160px;"
                v-model="articleFrom.createBy">
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="发布时间" prop="releaseTime">
              <el-date-picker
                style="width: 160px;"
                v-model="articleFrom.releaseTime"
                type="date"
                :clearable="true"
                value-format="yyyy-MM-dd"
                format="yyyy-MM-dd">
              </el-date-picker>
            </el-form-item>
            <el-form-item label="置顶" prop="topping">
              <el-switch
                :active-value="1"
                :inactive-value="0"
                v-model="articleFrom.topping">
              </el-switch>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="封面图（只能上传jpeg/jpg/png文件）" prop="pic">
              <el-upload
                class="avatar-uploader"
                accept="image/jpeg,image/jpg,image/png"
                :action="uploadUrl"
                :headers="headerObj"
                :show-file-list="false"
                :on-success="handleAvatarSuccess"
                :before-upload="beforeAvatarUpload">
                <img v-if="articleFrom.pic" :src="articleFrom.pic" class="avatar">
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
              </el-upload>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="文章内容" prop="content">
<!--          <editor-->
<!--            :height="300"-->
<!--            :minHeight="300"-->
<!--            :readOnly="false"-->
<!--            :fileSize="20"-->
<!--            v-model="articleFrom.content"-->
<!--          />-->
          <wang-editor
            v-if="showEditor"
            v-model="articleFrom.content"
            :editorConfig="editorConfig"
          />
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="handleCancel">取 消</el-button>
        <el-button type="primary" @click="handleSave">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog
      :visible.sync="dialogArticleVisible"
      title="新闻预览"
      width="1000px"
      top="5vh">
      <div class="articleArea">
        <p class="article_title">{{ ArticleTitle }}</p>
        <p class="article_date">{{ ArticleDate }}</p>
        <p class="article_content" v-html="ArticleContent"></p>
      </div>
      <span slot="footer">
        <el-button @click="dialogArticleVisible = false">关闭</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import WangEditor from "@/components/WangEditor/index.vue";
import {deleteArticleList, editArticleList, getArticleList, newArticleList} from '@/api/student'
import { importFile } from "@/api/student";
import {getToken} from "@/utils/auth";
import mixin from '@/views/mixin';
export default {
  components: {WangEditor},
  mixins: [mixin],
  data() {
    return {
      searchParams: {
        title: "",
        type: "",
        pageNum: 1,
        pageSize: 100,
      },
      tableData: [],
      total: 0,

      //封面图
      uploadUrl: "http://zs.xmafkj.com:4430/prod-api/common/upload",
      headerObj: { Authorization: getToken() },

      //新增文章
      dialogVisible: false,
      dialogTitle: '新增文章',
      articleFrom: {
        id: "",
        title: "",
        type: "",
        createBy: "",
        releaseTime: "",
        pic: "",
        topping: 1,
        content: "",
      },
      articleRules: {
        title: [
          { required: true, message: '请输入文章标题', trigger: 'change' },
        ],
        type: [
          { required: true, message: '请选择文章栏目', trigger: 'change' }
        ],
        content: [
          { required: true, message: '请输入文章内容', trigger: 'change' }
        ],
      },

      //预览文章
      dialogArticleVisible: false,
      ArticleTitle: "",
      ArticleDate: "",
      ArticleContent: "",

      //wangEditor
      showEditor: false,
      editorConfig: {
        placeholder: "请输入内容...",
        // 在编辑器中，点击选中“附件”节点时，要弹出的菜单
        hoverbarKeys: {
          attachment: {
            menuKeys: ["downloadAttachment"], // “下载附件”菜单
          },
        },
        MENU_CONF: {
          // “上传附件”菜单的配置
          uploadAttachment: {
            // 用户自定义上传
            customUpload(file, insertFn) {
              let formData = new FormData();
              formData.append("file", file);
              importFile("/common/upload", formData)
                .then((res) => {
                  const { url } = res;
                  insertFn(`${file.name}`, url);
                })
                .catch((error) => {});
            },
            // 插入到编辑器后的回调
            onInsertedAttachment(elem) {
              console.log("inserted attachment", elem);
            },
          },
          uploadImage: {
            //自定义上传，原因是需要设置上传文件名
            customUpload(file, insertFn) {
              const timeStamp = new Date() - 0;
              const copyFile = new File([file], `${timeStamp}_${file.name}`);
              let formData = new FormData();
              formData.append("file", copyFile);
              importFile("/common/upload", formData)
                .then((res) => {
                  const { url } = res;
                  insertFn(url);
                })
                .catch((error) => {});
            },
          },
          uploadVideo: {
            // 自定义上传
            customUpload(file, insertFn) {
              const timeStamp = new Date() - 0;
              const copyFile = new File([file], `${timeStamp}_${file.name}`);
              let formData = new FormData();
              formData.append("file", copyFile);
              importFile("/common/upload", formData)
                .then((res) => {
                  const { url } = res;
                  insertFn(url);
                })
                .catch((error) => {});
            },
          },
        },
      }
    }
  },
  created() {
    this.initTable();
  },
  methods: {
    initTable() {
      getArticleList(this.searchParams).then(res => {
        const { code, rows, total } = res;
        if(code === 200) {
          this.tableData = rows;
          this.total = total;
        }
      })
    },
    findColumnName(type) {
      if(this.columnList.some(item => item.value == type)) {
        return this.columnList.filter(item => item.value == type)[0].name
      }else {
        return '-'
      }
    },
    handleSearch() {
      this.initTable();
    },
    handleSizeChange(v) {
      this.searchParams.pageNum = 1;
      this.searchParams.pageSize = v;
      this.initTable();
    },
    handleCurrentChange(v) {
      this.searchParams.pageNum = v;
      this.initTable();
    },

    handleCheckItem(data) {
      const { content, createBy, releaseTime, pic, title, topping, type } = data;
      this.dialogArticleVisible = true;
      this.ArticleTitle = title;
      this.ArticleDate = releaseTime;
      this.ArticleContent = content;
    },
    handleEditItem(data) {
      const { id, content, createBy, releaseTime, pic, title, topping, type } = data;

      console.log(data)

      this.dialogVisible = true;
      this.showEditor = true;
      this.dialogTitle = "编辑文章";
      this.articleFrom.id = id;
      this.articleFrom.title = title;
      this.articleFrom.type = type;
      this.articleFrom.createBy = createBy;
      this.articleFrom.releaseTime = releaseTime;
      this.articleFrom.pic = pic;
      this.articleFrom.topping = topping;
      this.articleFrom.content = content;
    },
    handleDeleteItem(data) {
      const { id } = data;
      this.$confirm('确定删除该文章?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteArticleList(id).then(res => {
          this.initTable();
          this.$message({
            type: 'success',
            message: '删除成功!'
          });
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    newItem() {
      this.dialogTitle = "新增文章";
      this.articleFrom.content = "";
      this.dialogVisible = true;
      this.showEditor = true;
    },
    handleCancel() {
      this.dialogVisible = false;
      this.showEditor = false;

      this.articleFrom.id = "";
      this.articleFrom.title = "";
      this.articleFrom.type = "";
      this.articleFrom.createBy = "";
      this.articleFrom.releaseTime = "";
      this.articleFrom.pic = "";
      this.articleFrom.topping = 1;
      this.articleFrom.content = "";

      this.$refs['article'].resetFields();
    },
    handleSave() {
      this.$refs['article'].validate(async (valid) => {
        if (valid) {
          if(this.articleFrom.id) {
            await editArticleList(this.articleFrom)
          }else {
            await newArticleList(this.articleFrom)
          }
          this.handleCancel();
          this.initTable();
          this.$message({
            type: 'success',
            message: '新增成功!'
          });
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    beforeAvatarUpload(file) {
      const isLt2M = file.size / 1024 / 1024 < 20;
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 20MB!');
      }
      return isLt2M;
    },
    handleAvatarSuccess(res, file) {
      const { originalFilename, newFileName, fileName, url } = res;
      this.articleFrom.pic = url;
    },
  }
}
</script>
<style lang="scss" scoped>
div.articleManager {
  div.operate {
    height: 36px;
    margin-bottom: 10px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    .name {
      font-size: 12px;
      margin-right: 10px;
      &:not(:first-child) {
        margin-left: 10px;
      }
    }
    .el-input {
      width: 180px;
    }
  }
  //文章预览
  div.articleArea {
    border-top: 1px dotted #ccc;
    p.article_title {
      font-size: 28px;
      color: #000000;
      text-align: center;
      margin-bottom: 30px;
    }
    p.article_date {
      font-size: 16px;
      color: #999999;
      text-align: center;
      margin-bottom: 54px;
    }
    p.article_content ::v-deep {
      p {
        font-size: 14px;
        color: #666666;
        line-height: 28px;
        text-align: justify;
        padding: 10px 0;
      }
      img {
        max-width: 100%;
        margin-bottom: -10px;
      }
      div[data-w-e-type=video] {
        text-align: center;
      }
    }
  }
}
</style>
<style>
//封面图上传
.avatar-uploader {

}
.avatar-uploader .el-upload {
  border: 1px dashed #acb0b8;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 380px;
  height: 110px;
  line-height: 110px;
  text-align: center;
}
.avatar {
  width: 380px;
  height: 110px;
  display: block;
}
</style>

